/**
 * Created by tangwen on 16/12/9.
 */


import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.sql.*;

public class Email {

    private static final String host = "smtp.sina.com";
    private static final String home_address = "tangwen1225@sina.com";
    private static final String password = "123456a";

    public static void sendMail(String target_address){
        Properties props  = System.getProperties();
        props.put("mail.smtp.ssl.enable", true);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(home_address, password);
            }
        });
        try {
            MimeMessage message =  new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(target_address));
            message.setSubject("Java");
            //message.setText("Do you like ice-cream?");
            MimeBodyPart text = new MimeBodyPart();
            text.setContent("Do you like ice-cream</br><img src='cid:theIceCream'>", "text/html;charset=gb2312");
            MimeBodyPart img = new MimeBodyPart();
            DataHandler ah = new DataHandler(new FileDataSource("src//ice-cream.jpg"));
            img.setDataHandler(ah);
            MimeBodyPart theFile = new MimeBodyPart();
            //添加附件
            theFile.attachFile(new File("src//小图－甜点.psd"));
            img.setContentID("theIceCream");

            //将几个part合在一起。
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(text);
            mp.addBodyPart(img);
            mp.addBodyPart(theFile);
            mp.setSubType("related");
            message.setContent(mp);
            Transport.send(message);
        }catch (MessagingException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getReply() throws MessagingException {
        Properties props = new Properties();
        props.put("mail.pop3.ssl.enable", true);
        props.put("mail.pop3.host", "pop.sina.com");
        props.put("mail.pop3.auth", "true");
        Session session = Session.getDefaultInstance(props);

        Store store = null;
        Folder folder = null;

        try {
            store = session.getStore("pop3");
            store.connect(home_address, password);

            folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);

            int size = folder.getMessageCount();
            Message message = folder.getMessage(size);

            String from = message.getFrom()[0].toString();
            // 解码
            from = MimeUtility.decodeText(from);
            String subject = message.getSubject();

            System.out.println("From: " + from);
            System.out.println("Subject: " + subject);
            System.out.print("Content:    " );
            writePart(message);

        }catch (NoSuchProviderException e){
            e.printStackTrace();
        }catch (MessagingException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (folder != null){
                    folder.close(false);
                }
                if (store != null){
                    store.close();
                }
            }catch (MessagingException e){
                e.printStackTrace();
            }
        }
    }
    //对content进行解析。
    public static void writePart(Part message) throws Exception{
        if (message.isMimeType("text/plain")){
            String reply = (String) message.getContent();
            System.out.println(reply);
            //通过回复内容判断是否like ice-cream
            if (reply.indexOf("yes") != -1||reply.indexOf("Yes") != -1){
                System.out.println("He/She likes ice-cream");
            }else {
                System.out.println("He/She does't like ice-cream");
            }
        }else if (message.isMimeType("multipart/*")){
            Multipart mp = (Multipart) message.getContent();
            int mpSize = mp.getCount();
            for (int i = 0; i < mpSize; i++) {
                writePart(mp.getBodyPart(i));
            }
        }else if (message.isMimeType("message/rfc822")){
            System.out.println("This is a Nested Message");
            writePart((Part) message.getContent());
        }
    }

    public static void mailTest(){
        String driver = "com.mysql.jdbc.Driver";
        String dbName = "new_schema";
        String password = "123456a";
        String userName = "root";
        String url = "jdbc:mysql://localhost:3306/" + dbName;
        String sql = "select * from newTable";

        try {
            Connection conn = DriverManager.getConnection(url, userName, password);
            PreparedStatement pst = conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            while (rs.next()){
                sendMail(rs.getString(2));
            }
            if (rs != null){
                try {
                    rs.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if (pst != null){
                try {
                    pst.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws MessagingException {
        Email.mailTest();

        //Email.getReply();
    }
}
